import { convertUrl, oas3ClientsUrl, swagger2ClientsUrl } from '@/config'
import ora from 'ora'
import axios from 'axios'
import YAML from 'js-yaml'
import { ApiDoc, ConvertRes, ReadApiDocsRes } from '@/tsHelpers'
export const C_convert = async (lastData: ReadApiDocsRes) => {
  const startMsg = '数据处理中... \n'
  const errMsg = '数据处理失败 \n'
  const successMsg = '数据处理成功 \n'

  const spinner = ora(startMsg).start()

  let apiDocs: Array<ApiDoc | undefined> = []
  try {
    apiDocs = await Promise.all(
      lastData.apiDatas.map((item) => {
        return new Promise<ApiDoc | undefined>(async (resolve) => {
          if (!item) {
            resolve(undefined)
            return
          }
          const specOrigin = YAML.dump(YAML.load(item.originJson), {
            lineWidth: -1,
          })
          let spec: any = {}
          let isOAS3 = item.isOAS3
          const lang = lastData.client_type
          // 转换YAML
          if (!isOAS3 && lastData.convert) {
            const res = await axios.post(convertUrl, specOrigin, {
              headers: {
                'Content-Type': 'application/yaml',
                Accept: 'application/yaml',
              },
            })
            spec = YAML.load(res.data)
            isOAS3 = true
          } else {
            spec = YAML.load(specOrigin)
          }
          // client类型校验
          let clients: string[] = []
          clients = (await axios.get(isOAS3 ? oas3ClientsUrl : swagger2ClientsUrl)).data
          if (clients.findIndex((item) => item == lang) == -1) {
            throw new Error('client_type 参数有误, 无法生成相应类型的文件')
          }
          resolve({
            ...item,
            isOAS3,
            spec,
            lang,
            type: 'CLIENT',
          })
        })
      })
    )
    spinner.succeed(successMsg)
  } catch (error) {
    spinner.fail(errMsg)
    apiDocs = []
    throw error
  }
  return {
    ...lastData,
    apiDocs,
  } as ConvertRes
}
